package main

import (
	"os"
	"os/exec"
	"strings"
	"time"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
)

func main() {
	for {
		updateDNS()
		time.Sleep(time.Second * 300)
	}
}

//get host ipv6 address
func getHostIpv6Address() (string, error) {

	cmd := exec.Command("curl", "ifconfig.me")
	output, _ := cmd.Output()
	return string(output), nil
	// hc := http.Client{}
	// rc, err := hc.Get("http://ifconfig.me")
	// if err != nil {
	// 	return "", err
	// }
	// body, _ := ioutil.ReadAll(rc.Body)
	// return string(body), nil
	// addrs, err := net.InterfaceAddrs()
	// if err != nil {
	// 	return "", err
	// }
	// for _, addr := range addrs {
	// 	ipNet, isIPNet := addr.(*net.IPNet)
	// 	if isIPNet && !ipNet.IP.IsLoopback() {
	// 		if ipNet.IP.To4() == nil && ipNet.IP.IsGlobalUnicast() {
	// 			return ipNet.IP.String(), nil
	// 		}
	// 	}
	// }
	// return "", errors.New("not found")
}

var hostAddress = ""

//Update DNS
func updateDNS() {
	newAddr, err := getHostIpv6Address()
	println(newAddr)
	if err != nil {
		println(err.Error())
		return
	}
	if hostAddress == newAddr {
		return
	}
	client, err := alidns.NewClientWithAccessKey("cn-shanghai", "LTAI4G28UdkQcVcfWUSdtk2b", "YCGQrcTrQ8HMLDGJzAgOFWq0kzd5ER")
	if err != nil {
		println(err.Error())
		return
	}
	println("CreateDescribeDomainRecordsRequest")
	request := alidns.CreateDescribeDomainRecordsRequest()
	request.Scheme = "https"
	request.DomainName = "zuo.homes"
	request.Type = "AAAA"

	println("DescribeDomainRecords")
	response, err := client.DescribeDomainRecords(request)
	if err != nil {
		println(err.Error())
		return
	}
	println("Update dns...")
	for _, re := range response.DomainRecords.Record {
		//update domain record
		if strings.EqualFold(re.Value, newAddr) {
			println("Do not need update.")
			continue
		}
		updateRequest := alidns.CreateUpdateDomainRecordRequest()
		updateRequest.RecordId = re.RecordId
		updateRequest.RR = re.RR
		updateRequest.Type = re.Type
		updateRequest.Value = newAddr
		updateRequest.Line = re.Line
		updateRequest.UserClientIp = newAddr
		res, err := client.UpdateDomainRecord(updateRequest)
		if err != nil {
			return
		}
		if res.IsSuccess() {
			println("Succeed to update address")
		}
		if len(os.Args) > 1 {
			exec.Command(os.Args[1])
		}
	}
	hostAddress = newAddr
}
